import "package:flutter/material.dart";
import "package:myapp/_common/geyTextPainter.dart";
import 'package:waterfall_flow/waterfall_flow.dart'; //瀑布流
import "../../../_widget/swiper.dart";

class WaterfallItemTagItem {
  String name; //标签名称
  int color; //16进制颜色
  bool isRankingTag; //是否为排行标签
  String rank; //排行
  bool isSeries; //是否为系列
  WaterfallItemTagItem({
    required this.name,
    required this.color,
    this.isRankingTag = false,
    this.isSeries = false,
    this.rank = '',
  });
}

class WaterfallHotIP {
  String name; //IP名称
  String commodityCount; //商品数量
  String likeCount; //喜欢的人数量
  List<String> coverList; //封面(多图下为循环切换动画)
  String backgroundImageUrl; //背景图
  int themeColor; //16进制颜色
  WaterfallHotIP({
    required this.name,
    required this.commodityCount,
    required this.likeCount,
    required this.coverList,
    required this.backgroundImageUrl,
    required this.themeColor,
  });
}

//精彩评论
class WaterfallHotComment {
  String cover; //评论封面
  String username; //评论用户
  String comment; //评论内容
  String likeCount; //点赞数量
  String avatar; //评论用户头像
  WaterfallHotComment({
    required this.cover,
    required this.username,
    required this.comment,
    required this.likeCount,
    required this.avatar,
  });
}

class WaterfallItem {
  String cover; //封面
  String title; //标题
  List<WaterfallItemTagItem>? tagList; //标签
  String price; //价格
  bool isDeliveryPrice; //是否显示“到手价”
  bool isPriceStart; //是否显示xxx“起”
  bool isLuckBlindBox; //是否为欧气盲盒
  String? likeCount; //喜欢数量
  WaterfallHotIP? hotIP; //热门ip
  WaterfallHotComment? hotComment;
  String? subTitle; //小标题
  WaterfallItem({
    required this.cover,
    required this.title,
    this.tagList,
    required this.price,
    this.isDeliveryPrice = false,
    this.isPriceStart = false,
    this.isLuckBlindBox = false,
    this.likeCount,
    this.hotIP,
    this.hotComment,
    this.subTitle,
  });
}

class WaterfallListWidget extends StatelessWidget {
  final List<WaterfallItem> list = [
    WaterfallItem(
      title: "余量预售 BANPRESTO",
      cover: "./images/1.jpg",
      price: '129',
      likeCount: '404',
      isDeliveryPrice: true,
      tagList: [
        WaterfallItemTagItem(
          name: '满额权益',
          color: 0xFFF287E0,
        ),
        WaterfallItemTagItem(
          name: '偶像大师灰姑娘',
          color: 0xFFF287E0,
          isRankingTag: true,
          isSeries: true,
          rank: "16",
        ),
      ],
    ),
    WaterfallItem(
      title: "跨境余量预售 Ryu-NS 出包王女",
      cover: "./images/2.jpg",
      price: '129',
      likeCount: '1.4万',
      isPriceStart: true,
      tagList: [
        WaterfallItemTagItem(
          name: '满额权益',
          color: 0xFFF287E0,
        ),
        WaterfallItemTagItem(
          name: '出包王女',
          color: 0xFFF287E0,
          isRankingTag: true,
          isSeries: true,
          rank: '6',
        ),
      ],
    ),
    WaterfallItem(
      title: "余量预售 Reverse Studio 桌面",
      cover: "./images/3.jpg",
      price: '299',
      likeCount: '404',
      tagList: [
        WaterfallItemTagItem(
          name: '满额权益',
          color: 0xFFF287E0,
        ),
        WaterfallItemTagItem(
          name: '在地下城寻找邂逅是否搞错了什么',
          color: 0xFFF287E0,
          isRankingTag: true,
          isSeries: true,
          rank: '1',
        ),
      ],
    ),
    WaterfallItem(
      title: "预售 OMH 幻塔 凜夜 1/7 比例",
      cover: "./images/1.jpg",
      price: '269',
      likeCount: '1876',
      tagList: [
        WaterfallItemTagItem(
          name: '满额权益',
          color: 0xFFF287E0,
        ),
        WaterfallItemTagItem(
          name: '上新17天',
          color: 0xFFF287E0,
        ),
        WaterfallItemTagItem(
          name: '延期无忧',
          color: 0xFFF287E0,
        ),
      ],
    ),
    WaterfallItem(
      title: "",
      cover: "",
      price: '',
      hotComment: WaterfallHotComment(
          cover: './images/1.jpg',
          username: '秋深之处有人来',
          comment: "嘿嘿嘿，到了到了，爱了爱了\np.s.书角有些折痕，算是一些小瑕疵吧。但是，瑕不掩瑜啊！！！",
          likeCount: "6",
          avatar: './images/tab_1.jpg'),
    ),
    WaterfallItem(
      title: "雪未来 SNOW MIKU",
      cover: "./images/1.jpg",
      price: '72',
      likeCount: '1876',
      isLuckBlindBox: true,
      tagList: [
        WaterfallItemTagItem(
          name: '一番赏',
          color: 0xFFF287E0,
          isRankingTag: true,
          rank: "2",
        ),
      ],
    ),
    WaterfallItem(
      title: "",
      cover: "",
      price: '',
      hotIP: WaterfallHotIP(
        name: '轻音少女',
        commodityCount: "18",
        likeCount: '5280',
        coverList: [
          './images/1.jpg',
          './images/2.jpg',
          './images/3.jpg',
        ],
        backgroundImageUrl: "./images/2.jpg",
        themeColor: 0xFF24316C,
      ),
    ),
    WaterfallItem(
      title: "余量预售 BANPRESTO",
      cover: "./images/1.jpg",
      price: '129',
      likeCount: '404',
      isDeliveryPrice: true,
      tagList: [
        WaterfallItemTagItem(
          name: '满额权益',
          color: 0xFFF287E0,
        ),
        WaterfallItemTagItem(
          name: '偶像大师灰姑娘',
          color: 0xFFF287E0,
          isRankingTag: true,
          isSeries: true,
          rank: "16",
        ),
      ],
    ),
    WaterfallItem(
      title: "跨境余量预售 Ryu-NS 出包王女",
      cover: "./images/2.jpg",
      price: '129',
      likeCount: '1.4万',
      isPriceStart: true,
      tagList: [
        WaterfallItemTagItem(
          name: '满额权益',
          color: 0xFFF287E0,
        ),
        WaterfallItemTagItem(
          name: '出包王女',
          color: 0xFFF287E0,
          isRankingTag: true,
          isSeries: true,
          rank: '6',
        ),
      ],
    ),
    WaterfallItem(
      title: "余量预售 Reverse Studio 桌面",
      cover: "./images/3.jpg",
      price: '299',
      likeCount: '404',
      tagList: [
        WaterfallItemTagItem(
          name: '满额权益',
          color: 0xFFF287E0,
        ),
        WaterfallItemTagItem(
          name: '在地下城寻找邂逅是否搞错了什么',
          color: 0xFFF287E0,
          isRankingTag: true,
          isSeries: true,
          rank: '1',
        ),
      ],
    ),
    WaterfallItem(
      title: "预售 OMH 幻塔 凜夜 1/7 比例",
      cover: "./images/1.jpg",
      price: '269',
      likeCount: '1876',
      tagList: [
        WaterfallItemTagItem(
          name: '满额权益',
          color: 0xFFF287E0,
        ),
        WaterfallItemTagItem(
          name: '上新17天',
          color: 0xFFF287E0,
        ),
        WaterfallItemTagItem(
          name: '延期无忧',
          color: 0xFFF287E0,
        ),
      ],
    ),
    WaterfallItem(
      title: "",
      cover: "",
      price: '',
      hotComment: WaterfallHotComment(
          cover: './images/1.jpg',
          username: '秋深之处有人来',
          comment: "嘿嘿嘿，到了到了，爱了爱了\np.s.书角有些折痕，算是一些小瑕疵吧。但是，瑕不掩瑜啊！！！",
          likeCount: "6",
          avatar: './images/tab_1.jpg'),
    ),
    WaterfallItem(
      title: "雪未来 SNOW MIKU",
      cover: "./images/1.jpg",
      price: '72',
      likeCount: '1876',
      isLuckBlindBox: true,
      tagList: [
        WaterfallItemTagItem(
          name: '一番赏',
          color: 0xFFF287E0,
          isRankingTag: true,
          rank: "2",
        ),
      ],
    ),
    WaterfallItem(
      title: "",
      cover: "",
      price: '',
      hotIP: WaterfallHotIP(
        name: '轻音少女',
        commodityCount: "18",
        likeCount: '5280',
        coverList: [
          './images/1.jpg',
          './images/2.jpg',
          './images/3.jpg',
        ],
        backgroundImageUrl: "./images/2.jpg",
        themeColor: 0xFF24316C,
      ),
    ),
  ];
  final double phoneMaxWidth = 420; //判断为手机的最大宽度
  final double padMaxWidth = 840; //判断为平板的最大宽度
  WaterfallListWidget({super.key});
  @override
  Widget build(BuildContext context) {
    double maxwidth = MediaQuery.of(context).size.width;
    int column = maxwidth > 400 ? 3 : 2;
    double spacing = 6;
    return SliverWaterfallFlow.count(
      crossAxisCount: column,
      mainAxisSpacing: spacing,
      crossAxisSpacing: spacing,
      children: list
          .map((e) => ClipRRect(
                borderRadius: BorderRadius.circular(6),
                child: Container(
                  width: (maxwidth - (column - 1) * spacing) / column,
                  decoration: const BoxDecoration(color: Colors.white),
                  child: e.hotIP != null
                      ? WaterfallItemHopIPWidget(e: e.hotIP as WaterfallHotIP)
                      : e.hotComment != null
                          ? WaterfallHotCommentWidget(
                              e: e.hotComment as WaterfallHotComment)
                          : WaterfallItemShopWidget(e: e),
                ),
              ))
          .toList(),
    );
  }
}

// 一般商品
class WaterfallItemShopWidget extends StatelessWidget {
  final WaterfallItem e;
  const WaterfallItemShopWidget({super.key, required this.e});
  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        e.cover != ''
            ? Image.asset(
                e.cover,
                width: double.infinity,
                fit: BoxFit.fitWidth,
              )
            : const SizedBox(),
        Padding(
          padding: const EdgeInsets.fromLTRB(10, 6, 10, 6),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              Padding(
                padding: const EdgeInsets.only(bottom: 6),
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    e.isLuckBlindBox
                        ? Container(
                            padding: const EdgeInsets.fromLTRB(3, 1, 3, 1),
                            margin: const EdgeInsets.only(right: 3),
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(6),
                              gradient: LinearGradient(
                                colors: [
                                  Colors.blue,
                                  Colors.purple.shade300,
                                  Colors.purple.shade500
                                ],
                              ),
                            ),
                            child: const Text(
                              '欧气盲盒',
                              style: TextStyle(
                                color: Colors.white,
                                fontSize: 10,
                              ),
                            ),
                          )
                        : const SizedBox(),
                    Expanded(
                      flex: 1,
                      child: Text(
                        e.title,
                        maxLines: 1,
                        overflow: TextOverflow.clip,
                        style: const TextStyle(fontSize: 14),
                      ),
                    ),
                  ],
                ),
              ),
              Padding(
                padding: const EdgeInsets.only(bottom: 6),
                child: e.tagList != null
                    ? TextTagList(
                        tagList: e.tagList as List<WaterfallItemTagItem>)
                    : const SizedBox(),
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  RichText(
                    text: TextSpan(
                      children: [
                        TextSpan(
                          text: e.isDeliveryPrice ? '到手价' : '',
                          style: const TextStyle(
                            color: Colors.pink,
                            fontSize: 12,
                          ),
                        ),
                        TextSpan(
                          children: [
                            const TextSpan(
                              text: '¥',
                              style: TextStyle(
                                color: Colors.pink,
                                fontSize: 13,
                              ),
                            ),
                            TextSpan(
                              text: e.price,
                              style: const TextStyle(
                                color: Colors.pink,
                                fontSize: 16,
                                fontWeight: FontWeight.bold,
                              ),
                            )
                          ],
                        ),
                        TextSpan(
                          text: e.isPriceStart ? '起' : '',
                          style: const TextStyle(
                            color: Colors.pink,
                            fontSize: 12,
                          ),
                        ),
                      ],
                    ),
                  ),
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      const Icon(
                        Icons.heart_broken_outlined,
                        color: Colors.black45,
                        size: 18,
                      ),
                      Text(
                        e.likeCount ?? '',
                        style: const TextStyle(
                          color: Colors.black45,
                          fontSize: 13,
                        ),
                      ),
                    ],
                  )
                ],
              ),
            ],
          ),
        )
      ],
    );
  }
}

// 单行文本标签
class TextTagList extends StatelessWidget {
  final List<WaterfallItemTagItem> tagList;
  final int limitTextLength = 3; //标签文字缩略后至少要3字以上(不包含类型文字)
  final double tagPaddingHorizontal = 3; //水平方向上的内边距
  final double tagSpacing = 4; //水平方向标签间间隔
  final double tagTextFontSize = 10;
  const TextTagList({
    super.key,
    required this.tagList,
  });
  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
        builder: (BuildContext context, BoxConstraints container) {
      double maxWidth = container.maxWidth; //容器宽度
      double tagWidth = 0; //累计标签宽度（包含边距等）
      List<String> tagTextList = []; //显示标签文字（按顺序插入）

      // 遍历计算显示的标签的文字宽度
      for (int i = 0; i < tagList.length; i++) {
        var tag = tagList[i];
        String endText = (tag.isSeries ? '系列' : '') +
            (tag.isRankingTag ? '榜No.${tag.rank}' : '');
        String text = tag.name + endText;
        final textPainer = getTextPainter(
          context,
          text: text,
          maxLines: 1,
          style: TextStyle(fontSize: tagTextFontSize),
          maxWidth: maxWidth - tagWidth,
        );
        double needWidth =
            textPainer.width + tagSpacing + 2 * tagPaddingHorizontal;

        if (needWidth > maxWidth - tagWidth) {
          // 如果需求宽度大于剩余宽度
          // 如果是系列或者榜,则尝试从后往前移除至至少“3”个字的最长可满足宽度
          // 此时的需求宽度要加上省略的宽度
          if (tag.isSeries || tag.isRankingTag) {
            for (int j = tag.name.length - 1;
                j >= tagPaddingHorizontal - 1;
                j--) {
              String afterString =
                  '${tag.name.substring(0, j)}...$endText'; //裁剪合并后字符串
              // 重新判断当前宽度
              final textPainer = getTextPainter(
                context,
                text: afterString,
                maxLines: 1,
                style: TextStyle(fontSize: tagTextFontSize),
                maxWidth: maxWidth - tagWidth,
              );
              double needWidth = textPainer.width +
                  tagSpacing +
                  2 * tagPaddingHorizontal; //整理后的实际宽度
              if (needWidth > maxWidth - tagWidth) {
                // 如果整理后的宽度还是不满足，则继续
                continue;
              } else {
                // 此时已满足宽度需求
                tagTextList.add(afterString);
                tagWidth += needWidth;
                break;
              }
            }
          } else {
            break;
          }
        } else {
          tagTextList.add(text);
          tagWidth += needWidth;
        }
      }

      List<Widget> children = [];
      for (int i = 0; i < tagTextList.length; i++) {
        var tag = tagList[i];
        children.add(Container(
          padding: EdgeInsets.fromLTRB(
            tagPaddingHorizontal,
            1,
            tagPaddingHorizontal,
            1,
          ),
          decoration: BoxDecoration(
            color: Color(tag.color - 0xcc000000),
            borderRadius: BorderRadius.circular(3),
          ),
          child: Text(
            tagTextList[i],
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style:
                TextStyle(fontSize: tagTextFontSize, color: Color(tag.color)),
          ),
        ));
      }

      return Wrap(spacing: tagSpacing, children: children);
    });
  }
}

// 热门IP
class WaterfallItemHopIPWidget extends StatefulWidget {
  final WaterfallHotIP e;
  const WaterfallItemHopIPWidget({super.key, required this.e});
  @override
  State<StatefulWidget> createState() {
    return _WaterfallItemHopIPWidgetState();
  }
}

class _WaterfallItemHopIPWidgetState extends State<WaterfallItemHopIPWidget> {
  bool visible = true;
  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage(widget.e.backgroundImageUrl),
          fit: BoxFit.cover,
        ),
      ),
      child: Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            colors: [
              Color(widget.e.themeColor - 0x11000000),
              Color(widget.e.themeColor - 0x22000000),
              Color(widget.e.themeColor - 0x33000000),
              Color(widget.e.themeColor - 0x44000000),
              Color(widget.e.themeColor - 0x55000000),
              Color(widget.e.themeColor - 0x66000000),
              Color(widget.e.themeColor - 0x77000000),
              Color(widget.e.themeColor - 0x88000000),
            ],
            begin: Alignment.bottomCenter,
            end: Alignment.topCenter,
          ),
        ),
        child: Column(
          children: [
            AspectRatio(
              aspectRatio: 1,
              // child: Image.asset(
              //   widget.e.coverList[0],
              //   fit: BoxFit.cover,
              // ),
              child: LayoutBuilder(builder: (
                BuildContext context,
                BoxConstraints constraints,
              ) {
                // return Image.asset(
                //   widget.e.coverList[0],
                //   fit: BoxFit.cover,
                // );
                return IgnorePointer(
                  child: Swiper(
                    height: constraints.maxHeight,
                    loop: true,
                    auto: true,
                    onCurrentIndexChange: (val) {},
                    isFade: true,
                    children: widget.e.coverList
                        .map((e) => Image.asset(e, fit: BoxFit.cover))
                        .toList(),
                  ),
                );
              }),
            ),
            Padding(
              padding: const EdgeInsets.all(8),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                    width: 56,
                    padding: const EdgeInsets.all(2),
                    margin: const EdgeInsets.only(bottom: 6),
                    decoration: BoxDecoration(
                      color: const Color.fromARGB(185, 181, 181, 181),
                      borderRadius: BorderRadius.circular(10),
                    ),
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        CircleAvatar(
                          radius: 6,
                          backgroundColor: Colors.white,
                          child: Text(
                            'IP',
                            style: TextStyle(
                                fontSize: 8,
                                color: Color(widget.e.themeColor),
                                fontStyle: FontStyle.italic,
                                fontWeight: FontWeight.bold),
                          ),
                        ),
                        const Padding(
                          padding: EdgeInsets.only(left: 3),
                          child: Text(
                            '热门作品',
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: 8,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                  Container(
                    margin: const EdgeInsets.only(bottom: 6),
                    child: const Text(
                      '明日方舟',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 12,
                      ),
                    ),
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    crossAxisAlignment: CrossAxisAlignment.end,
                    children: [
                      Text(
                        '${widget.e.commodityCount}件商品',
                        style: const TextStyle(
                          color: Colors.white,
                          fontSize: 12,
                        ),
                      ),
                      Text(
                        '${widget.e.likeCount}人喜欢',
                        style: const TextStyle(
                          color: Colors.white,
                          fontSize: 12,
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            )
          ],
        ),
      ),
    );
  }
}

// 精彩评论
class WaterfallHotCommentWidget extends StatelessWidget {
  final WaterfallHotComment e;
  const WaterfallHotCommentWidget({super.key, required this.e});
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Stack(
          clipBehavior: Clip.none,
          children: [
            Image.asset(
              e.cover,
              fit: BoxFit.cover,
            ),
            Positioned(
              bottom: -8,
              left: 6,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  Container(
                    padding: const EdgeInsets.only(
                        left: 2, right: 2, top: 2, bottom: 2),
                    decoration: BoxDecoration(
                      color: Colors.pink,
                      borderRadius: BorderRadius.circular(10),
                    ),
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Container(
                          width: 13,
                          height: 13,
                          padding: const EdgeInsets.all(1),
                          margin: const EdgeInsets.only(right: 2),
                          decoration: BoxDecoration(
                              color: Colors.white,
                              borderRadius: BorderRadius.circular(6)),
                          child: const Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              Text(
                                '评',
                                style: TextStyle(
                                  color: Colors.pink,
                                  fontSize: 8,
                                  fontStyle: FontStyle.italic,
                                  fontWeight: FontWeight.bold,
                                ),
                              )
                            ],
                          ),
                        ),
                        const Text(
                          '精彩评论',
                          style: TextStyle(
                            fontSize: 8,
                            color: Colors.white,
                          ),
                        )
                      ],
                    ),
                  )
                ],
              ),
            ),
          ],
        ),
        const SizedBox(height: 10),
        Padding(
          padding:
              const EdgeInsets.only(left: 10, right: 10, top: 10, bottom: 0),
          child: RichText(
            maxLines: 3,
            overflow: TextOverflow.ellipsis,
            text: TextSpan(
              text: e.comment,
              style: const TextStyle(
                fontSize: 13,
                color: Colors.black87,
                height: 1.3,
              ),
            ),
          ),
        ),
        Padding(
          padding:
              const EdgeInsets.only(left: 10, right: 10, bottom: 10, top: 4),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Expanded(
                flex: 1,
                child: Row(
                  children: [
                    CircleAvatar(
                      radius: 8,
                      backgroundImage: AssetImage(e.avatar),
                    ),
                    Expanded(
                      flex: 1,
                      child: Padding(
                        padding: const EdgeInsets.only(left: 4),
                        child: Text(
                          e.username,
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: const TextStyle(
                            color: Colors.black38,
                            fontSize: 12,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              Row(
                children: [
                  const Icon(
                    Icons.heart_broken,
                    color: Colors.black38,
                    size: 18,
                  ),
                  Padding(
                    padding: const EdgeInsets.only(left: 2),
                    child: Text(
                      e.likeCount,
                      style: const TextStyle(
                        color: Colors.black38,
                        fontSize: 12,
                      ),
                    ),
                  ),
                ],
              )
            ],
          ),
        ),
      ],
    );
  }
}
